<template>
  <view>
    <!-- <up-navbar title="我的" bgColor="transparent" leftIcon=""> </up-navbar> -->
    <!-- #ifdef MP-WEIXIN -->
    <customNav
      class="z-[111] relative"
      style="position: relative; z-index: 888"
      :back="false"
      title="我的"
    ></customNav>
    <!-- #endif -->
    <view
      class="my-bg w-full"
      :style="{
        paddingTop: navHeight * 2 + 24 + 'rpx',
      }"
    >
      <view class="flex justify-between items-center pl-[36rpx] pr-5">
        <view class="flex justify-center items-center mt-[30rpx]">
          <image
            @click="goInfo"
            v-if="isLogin"
            :src="userInfo.avatar"
            class="w-[109rpx] h-[109rpx] rounded-full"
            mode="aspectFill"
          ></image>
          <image
            v-else
            @click="handleLogin"
            src="@/static/avatar.png"
            class="w-[109rpx] h-[109rpx] rounded-full"
          ></image>
          <view class="pl-3" @click="goInfo" v-if="isLogin">
            <view class="text-main text-lg font-medium">{{
              userInfo.nickname
            }}</view>
            <view class="text-[#979797] text-xs mt-[14rpx]">{{
              userInfo.mobile
            }}</view>
          </view>
          <view class="pl-3" @click="handleLogin" v-else>
            <view class="text-main text-lg">请登录</view>
          </view>
        </view>
        <view v-if="isLogin" @click="logOut" class="text-[#B8B8B8] text-xs"
          >退出登录</view
        >
      </view>
    </view>

    <view class="px-6 mt-[62rpx]">
      <view class="text-xl font-medium text-black mb-[30rpx]"
        >我保存的成绩</view
      >
      <template v-if="isLogin && list.length">
        <!-- <template> -->
        <view
          class="rounded-lg overflow-hidden"
          v-for="(item, index) in list"
          :key="index"
        >
          <view
            class="xunjia px-[30rpx] pt-4 pb-3 mb-3 overflow-hidden"
            @click="goDetail(item)"
          >
            <view
              class="flex justify-between items-center air pb-[28rpx] overflow-hidden"
            >
              <view class="flex items-center">
                <!-- <image src="@/static/flyAir.png" class="w-5 h-5"></image> -->
                <view class="text-[#1A1C1E] text-base font-medium">
                  {{ item.name }}
                </view>

                <view class="text-[#909399] text-xs pl-4 font-[300]">
                  保存于{{ item.update_time }}
                </view>
              </view>
              <image
                @click.stop="deleteScore(item.id)"
                src="@/static/close1.png"
                class="w-5 h-5"
              ></image>
            </view>
            <view class="flex justify-between text-4xl mt-[16rpx] items-center">
              <view class="">
                <view class="text-[#606266] text-base leading-[50rpx]"
                  >性别{{ item.sex }} / {{ item.items_total }}项</view
                >
                <view class="font-bold text-xl text-black leading-[56rpx]"
                  >总得分{{ item.score_total }}分</view
                >
              </view>
              <!-- <image
                class="h-[60rpx] mx-[44rpx] flex-1"
                src="@/static/airWay.png"
              ></image> -->
              <!-- <view
                class="text-[#909399] font-bold text-xl pr-5"
                v-if="item.feedback_status == 1"
                >待反馈</view
              >
              <view
                class="text-[#0CB7A3] font-bold text-xl pr-5"
                v-if="item.feedback_status == 2"
                >已反馈</view
              >
              <view
                class="text-[#303133] text-base rounded-[60rpx] py-[20rpx] px-5 leading-[32rpx]"
                style="border: 2rpx solid #dcdcdc"
                v-if="item.feedback_status == 0"
                @click.stop="zixun(item.id)"
              >
                <view>一键咨询 </view>
                <view>提高方案</view>
              </view> -->
            </view>
          </view>
        </view>
      </template>
      <view class="flex-1 flex justify-center items-center py-7" v-else>
        <up-empty
          textSize="16"
          textColor="#222222"
          text="暂无数据"
          icon="/static/empty.png"
          width="101"
          height="120"
        >
        </up-empty>
      </view>
    </view>

    <view class="px-6 mt-[68rpx]">
      <view class="text-xl font-medium text-black mb-[30rpx]"
        >多人批量计算任务</view
      >
      <template v-if="isLogin && fileList.length">
        <!-- <template> -->
        <view
          class="rounded-lg overflow-hidden"
          v-for="(item, index) in fileList"
          :key="index"
        >
          <view class="xunjia px-[30rpx] pt-4 pb-3 mb-3 overflow-hidden">
            <view
              class="flex justify-between items-center pb-[28rpx] overflow-hidden"
            >
              <view class="flex items-center">
                <!-- <image src="@/static/flyAir.png" class="w-5 h-5"></image> -->
                <view class="text-[#1A1C1E] text-base font-medium">
                  {{ item.name }}
                </view>
              </view>
              <image
                @click.stop="deleteFile(item.id)"
                src="@/static/close1.png"
                class="w-5 h-5"
              ></image>
            </view>
            <view class="flex justify-between text-4xl mt-[18rpx] items-center">
              <view class="">
                <view class="text-[#606266] text-base leading-[50rpx]">
                  任务编号：<text>{{ item.task_id }}</text></view
                >
                <view class="text-base text-[#606266] leading-[50rpx]">
                  创建时间：<text>{{ item.create_time }}</text></view
                >
                <view class="text-base text-[#606266] leading-[50rpx]">
                  完成时间：<text>{{ item.end_time || "-" }}</text></view
                >
              </view>
              <view
                class="text-[#909399] font-bold text-xl pr-5"
                v-if="item.end_time == '--'"
                >任务执行中</view
              >
              <view
                class="text-[#303133] text-base rounded-[60rpx] py-[20rpx] px-5 leading-[32rpx] font-bold"
                style="border: 2rpx solid #dcdcdc"
                v-else
                @click.stop="downLoadFIle(item.download_url)"
              >
                <view>下载Excel </view>
              </view>
            </view>
            <view class="text-base text-black leading-[54rpx] font-bold">
              总行数 / <text class="text-[#12D57D]">成功</text> /
              <text class="text-[#C8361C]">异常</text>：{{
                item.total_records
              }}
              / <text class="text-[#12D57D]">{{ item.success_records }}</text> /
              <text class="text-[#C8361C]">{{ item.error_records }}</text>
            </view>
          </view>
        </view>
      </template>
      <view class="flex-1 flex justify-center items-center py-7" v-else>
        <up-empty
          textSize="16"
          textColor="#222222"
          text="暂无数据"
          icon="/static/empty.png"
          width="101"
          height="120"
        >
        </up-empty>
      </view>
    </view>
    <u-modal
      confirmColor="#2D7DF2"
      confirmText="复制"
      :showCancelButton="true"
      :show="showDown"
      @confirm="copyUrl"
      @cancel="showDown = false"
    >
      <view class="px-2">
        <view class="text-[#303133] font-bold text-xl leading-[46rpx]">
          您当前在电脑中使用小程序，请复制 下面地址在浏览器中下载计算结果
        </view>
        <view
          class="mt-[30rpx] text-xs text-[#909399]"
          style="font-weight: 300; word-break: break-all"
        >
          {{ downUrl }}
        </view>
      </view>
    </u-modal>
    <!-- #ifdef MP-WEIXIN -->
    <customTab value="my" />
    <!-- #endif -->
  </view>
</template>

<script setup lang="ts">
import { throttle } from "lodash";
import { wexin_login_api } from "@/api/user.js";
import {
  scoreList_api,
  delScore_api,
  questionOnce_api,
  getBatchList_api,
  delBatch_api,
} from "@/api/index.js";
import { ref, reactive, computed } from "vue";
import { onPageScroll, onShow } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/user.js";
import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
const userStore = useUserStore();
onShareAppMessage(() => {
  return {
    title: "钧韬竞速",
    path: `/pages/index/index`,
  };
});

onShareTimeline(() => {
  return {
    title: "钧韬竞速",
    query: `/pages/index/index`,
  };
});
const isLogin = computed(() => userStore.isLogin);
const userInfo = computed(() => userStore.userInfo);

onPageScroll((e) => {});
const systemInfo = uni.getSystemInfoSync();
// #ifdef MP
// 获取胶囊按钮位置信息
const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// 计算导航栏高度（状态栏高度 + 胶囊按钮高度 + 上下边距）
const navHeight =
  menuButtonInfo.bottom + menuButtonInfo.top - systemInfo.statusBarHeight;
// #endif

// 创建响应式数据
const list1 = ref([
  { name: "公务包机" },
  { name: "团体包机" },
  { name: "医疗包机" },
  { name: "航空货运" },
  { name: "公务包机" },
  { name: "团体包机" },
  { name: "医疗包机" },
  { name: "航空货运" },
]);

const current = ref(0);

const goTab = (url) => {
  if (!isLogin.value) return uni.$u.toast("请先登录");
  uni.navigateTo({
    url: url,
  });
};

const login = () => {
  uni.navigateTo({
    url: "/pages/my/login",
  });
};
const goInfo = () => {
  uni.navigateTo({
    url: "/pages/my/info",
  });
};

const list = ref([]);
const getStatus = () => {
  scoreList_api().then((res) => {
    list.value = res;
  });
};

const fileList = ref([]);
const getFileList = () => {
  getBatchList_api().then((res) => {
    fileList.value = res;
  });
};

onShow(() => {
  if (isLogin.value) {
    getStatus();
    getFileList();
  }
});

const deleteScore = (id) => {
  uni.showModal({
    title: "温馨提示",
    content: "确定删除本条体育评分吗？",
    success: (res) => {
      if (res.confirm) {
        delScore_api(id).then((res) => {
          uni.$u.toast("删除成功");
          getStatus();
        });
      }
    },
  });
};

const deleteFile = (id) => {
  uni.showModal({
    title: "温馨提示",
    content: "确定删除本条任务吗？",
    success: (res) => {
      if (res.confirm) {
        delBatch_api(id).then((res) => {
          uni.$u.toast("删除成功");
          getFileList();
        });
      }
    },
  });
};

const goDetail = (item) => {
  uni.navigateTo({
    url: `/pages/my/detail?id=${item.id}&type=${item.score_type}`,
  });
};

const handleLogin = throttle(() => {
  uni.showLoading();
  uni.login({
    provider: "weixin",
    success: (res) => {
      wexin_login_api(res.code).then((resulit) => {
        if (resulit.code == 2) {
          login();
        } else {
          if (resulit.code == 0) {
            uni.$u.toast(resulit.msg);
            return;
          }
          userStore.getUser(resulit.data.userinfo);
          userStore.login(resulit.data.userinfo.token);
          getStatus();
          getFileList();
          const data = uni.getStorageSync("redirectUrl");
          if (data) {
            uni.navigateTo({
              url: `/pages/index/calculator?id=${data.area_id}&type=${data.score_type}&tab=${data.tab}`,
              success: () => {
                uni.removeStorageSync("redirectUrl");
              },
            });
          }
        }
      });
    },
    fail: (err) => {
      console.log(err);
    },
    complete: () => {
      uni.hideLoading();
    },
  });
}, 1000);
const logOut = () => {
  uni.showLoading();
  userStore.logout();
  setTimeout(() => {
    uni.hideLoading();
  }, 500);
};

const zixun = (id) => {
  questionOnce_api(id).then((res) => {
    uni.showModal({
      title: "温馨提示",
      content: "提交成功，请等待反馈",
      showCancel: false,
      success: () => {
        getStatus();
      },
    });
  });
};

const showDown = ref(false);
const downUrl = ref(false);
const platform = uni.getSystemInfoSync().platform;

const copyUrl = () => {
  uni.setClipboardData({
    data: downUrl.value,
    success: () => {
      uni.$u.toast("复制成功");
      showDown.value = false;
    },
  });
};

const downLoadFIle = (url) => {
  if (!url) return uni.$u.toast("暂无下载地址");

  if (platform == "windows" || platform == "mac") {
    showDown.value = true;
    downUrl.value = url;
    return;
  }
  uni.showLoading({
    title: "正在下载...",
  });
  const file = url;
  uni.downloadFile({
    //只能是GET请求
    url: file, //请求地址(后台返回的码流地址)
    // filePath: wx.env.USER_DATA_PATH + "/download/体育成绩.xlsx", //保存到本地的路径
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        uni.hideLoading(); //隐藏加载框
        //保存文件
        var tempFile = res.tempFilePath;
        console.log(tempFile, res, "tempFilePath");
        //保存成功之后 打开文件
        uni.openDocument({
          filePath: tempFile,
          showMenu: true, //微信小程序 downloadFile生成的tempFilePath为临时路径无法直接保存到手机 显示菜单设置可以手动保存到手机本地
          fail: (e) => {
            console.log(e, "打开失败");
            let nowEno = uni.getSystemInfoSync().platform; //当前环境
            console.log(e, "打开失败", nowEno);
            if (nowEno == "ios") {
              //ios打开临时路径文件失败 设置ios环境下读取临时路径文件可以打开
              uni.getFileSystemManager().readFile({
                filePath: tempFile,
                success: (res) => {
                  var filebuffer = res.data;
                  return filebuffer;
                },
                fail: console.error,
              });
            } else {
              uni.showToast({
                title: "打开失败",
              });
            }
          },
        });
      } else {
        uni.hideLoading();
      }
    },
    fail: (e) => {
      uni.hideLoading();
      console.log(e, "文件下载失败");
      uni.showToast({
        title: "文件下载失败",
        icon: "none",
      });
    },
  });
};
</script>

<style lang="scss" scoped>
:deep(.u-tabs__wrapper__nav__item) {
  padding-left: 30rpx !important;
  padding-right: 30rpx !important;
}
:deep(.u-tabs__wrapper__nav) {
  margin: 0 -30rpx;
}
:deep(.u-cell__body) {
  padding: 30rpx 0 !important;
  border-top: 2rpx solid #f7f7f7 !important;
}
:deep(.u-collapse-item__content__text) {
  padding: 24rpx 6rpx !important;
  color: #8d8d8d !important;
  font-size: 28rpx !important;
}
.my-bg {
  width: 100%;
  background: linear-gradient(180deg, #e1ebf7 0%, rgba(225, 235, 247, 0) 100%);
  border-radius: 0rpx 0rpx 0;
}
.xunjia {
  // height: 222rpx;
  background: linear-gradient(180deg, #ebefff 0%, #ffffff 100%);
  border-radius: 16rpx 16rpx 16rpx 16rpx;
  border: 2rpx solid;
  border-image: linear-gradient(
      180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0)
    )
    2 2;
  .air {
    border-bottom: 2rpx solid #f7f7f7;
  }
}
</style>
